import React, { Component } from 'react'
import InputField from './InputField'
import { Input, Button } from 'antd';
import { message } from 'antd';
import VerifyImageShow from './VerifyImageShow';
import { _enroll } from '../common/Api';
import { withRouter } from 'react-router-dom'
import md5 from 'md5'

const error = (msg) => {
    message.error(msg);
};

const success = () => {
    message.success('注册成功');
};

class Enroll extends Component {
    constructor(props) {
        super(props);
        this.state = {
            form: [
                {
                    placeholder: '请输入用户名',
                    icon: "anticonyonghu",
                    nullTip: '输入不能为空',
                    errorTip: '请输入英文作为你的用户名',
                    pattern: /[a-zA-Z]/,
                    isPassword: false,
                    type: 'username',
                    method: 'enroll'
                },
                {
                    placeholder: '请输入至少6位密码',
                    icon: "anticonziyuanxhdpi",
                    nullTip: '输入不能为空',
                    errorTip: '密码不能少于6位且不能包括中文',
                    pattern: /\w{6,}/,
                    isPassword: true,
                    type: 'password',
                    method: 'enroll'
                },
                {
                    placeholder: '请再次输入密码',
                    icon: "anticonziyuanxhdpi",
                    nullTip: '输入不能为空',
                    errorTip: '两次密码输入不一致',
                    pattern: null,
                    isPassword: true,
                    type: 'verifyPassword',
                    method: 'enroll'
                }
            ],
            // 用户输入的信息，用于保存以便验证
            // 依次为用户名和密码
            verifyObj: [
                {}, {}, {}
            ],
        }
    }

    // 接收InputField的数据
    handleTransformData = (data) => {
        let { verifyObj } = this.state;
        if (data.type === "username") {
            verifyObj[0] = data;
        } else if (data.type === "password") {
            verifyObj[1] = data;
        } else {
            verifyObj[2] = data;
        }

        this.setState({
            verifyObj
        });
    }

    // 以下两个函数实现页面hover功能
    handleMouseover = () => {
        this.elem.style.backgroundColor = 'rgba(255, 255, 255, 0.4)';
    }

    handleMouseout = () => {
        this.elem.style.backgroundColor = 'rgba(255, 255, 255, 0.3)';
    }

    // 点击注册，进行前端验证，并且跳转页面到登录页面
    hanleClick = () => {
        // 遍历查找verifyResult，如果全部为真，则传到后端进行用户验证
        const { verifyObj } = this.state;

        let count = 0; // 错误计数器
        verifyObj.map((item, index) => {
            if (!item.verifyResult) {
                count++;
            }
            return index;
        })

        if (verifyObj[1].value !== verifyObj[2].value) {
            error('两次密码输入不一致，请重新输入')
            return;
        }

        if (count) {
            error('请输入正确格式的用户名和密码');
            return;
        }

        this.enrollUser(verifyObj[0].value, md5(verifyObj[1].value), verifyObj[3].value);
    }

    // 注册接口
    async enrollUser(username, password, captcha) {
        let obj = {};
        obj.username = username;
        obj.password = password;
        obj.captcha = captcha;

        const res = await _enroll(obj);

        if (res.data.code === 0) {
            success();

            this.enterRegister()
        } else {
            error(res.data.message) // TODO：错误需刷新验证码
        }
    }

    // 保存验证码的数据
    saveVerifyData = () => {
        // 点击按钮，发起ajax请求
        const value = this.verifyNumber.input.value;

        // 创建临时对象存储验证码信息
        let obj = {};
        obj.verifyResult = true
        obj.value = value;

        let { verifyObj } = this.state;
        verifyObj[3] = obj;
        this.setState({
            verifyObj
        });
    }

    enterRegister = () => {
        this.props.enterRegister()
    }

    render() {
        return (
            <div style={{
                width: 400,
                height: 600,
                position: 'relative',
            }}>
                <div style={{
                    backgroundColor: 'rgba(33, 33, 33, 0.3)',
                    height: 450,
                    borderRadius: 5
                }}>
                    <div style={{
                        width: 350,
                        margin: '0 auto',
                        paddingTop: 20,
                        display: 'flex',
                        justifyContent: 'space-between',
                        paddingBottom: 20
                    }}>
                        <div style={{
                            color: '#ddd',
                            width: 150,
                            textAlign: 'center',
                            fontSize: 30,
                            cursor: 'pointer'
                        }} onClick={this.enterRegister}>登录</div>
                        <div style={{
                            color: '#fff',
                            width: 150,
                            textAlign: 'center',
                            fontSize: 30,
                            borderBottom: '3px solid white',
                            cursor: 'pointer',
                            paddingBottom: 10
                        }}>注册</div>
                    </div>
                    <InputField data={this.state.form[0]} transfornFun={this.handleTransformData} />
                    <InputField data={this.state.form[1]} transfornFun={this.handleTransformData} />
                    <InputField data={this.state.form[2]} transfornFun={this.handleTransformData} />
                    <div style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        marginRight: 25
                    }}>
                        <Input
                            placeholder="验证码"
                            style={{
                                width: 137,
                                height: 50,
                                marginTop: 0,
                                marginBottom: 20,
                                marginLeft: 25
                            }}
                            ref={(verifyNumber) => (this.verifyNumber = verifyNumber)}
                            onBlur={() => this.saveVerifyData()}
                            onPressEnter={this.saveVerifyData}
                        />
                        <VerifyImageShow />
                    </div>
                    <Button type="primary" style={{
                        marginLeft: 25,
                        width: 350,
                        height: 40,
                        fontSize: 20
                    }} onClick={() => { this.hanleClick() }}>注册</Button>
                </div>
            </div>
        )
    }
}

export default withRouter(Enroll);